package keeto.com.vn.bms.ui.fragment;


import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import keeto.com.vn.bms.config.BMSCore;
import keeto.com.vn.bms.config.IBMSConfig;
import keeto.com.vn.bms.model.BasePopupModel;
import keeto.com.vn.bms.model.CompanyModel;
import keeto.com.vn.bms.model.Hospital;
import keeto.com.vn.bms.model.HospitalRecordInputDataModel;
import keeto.com.vn.bms.model.InfoDoctorEntity;
import keeto.com.vn.bms.model.InputDataModel;
import keeto.com.vn.bms.model.MedicalRecordModel;
import keeto.com.vn.bms.model.User.Doctor;
import keeto.com.vn.bms.network.IBMSProtocol;
import keeto.com.vn.bms.ui.activity.R;
import keeto.com.vn.bms.ui.adapter.BasePopupAdapter;
import keeto.com.vn.bms.ui.adapter.ListHospitalAdapter;
import keeto.com.vn.bms.ui.adapter.ListInfoDoctorAdapter;
import keeto.com.vn.bms.ui.adapter.ListStatisticDoctorAdapter;
import keeto.com.vn.bms.ui.adapter.ListTypeScheduleAdapter;
import keeto.com.vn.bms.ui.widget.IPopupWindow;
import keeto.com.vn.bms.utils.BMSListener;
import keeto.com.vn.bms.utils.BMSSharedPreferences;
import keeto.com.vn.bms.utils.DateTimeSystem;
import keeto.com.vn.bms.utils.UtilityListView;
import keeto.com.vn.bms.utils.Utils;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

public class BMSDataEntryFragment extends BaseFragment implements
		OnClickListener {
	private BMSSharedPreferences mPreferences;
	private Listener listener = new Listener();
	private ArrayAdapter<String> adapterSpinInput;
	private ArrayAdapter<String> adapterSpinnerSelectCom;
	private Button spnSelectCom;
	private Button spnInputData;
	private LinearLayout lnTime;
	private LinearLayout lnSave;
	private LinearLayout lnTableDoctor;
	private LinearLayout lnTableHospital;
	private LinearLayout lnTableType;

	private ListView lvTableDoctor, lvTableHos, lvTableType;
	private EditText edtSelectTime;
	int hospitalPosition;

	private ArrayList<Doctor> doctors = new ArrayList<Doctor>();
	private ListStatisticDoctorAdapter lvDoctorAdapter;

	private ArrayList<Hospital> hospitals = new ArrayList<Hospital>();
	private ListHospitalAdapter lvHospitalAdapter;

	private ArrayList<MedicalRecordModel> records = new ArrayList<MedicalRecordModel>();
	private ListTypeScheduleAdapter lvTSAdapter;
	private ArrayList<CompanyModel> listCompanies = new ArrayList<CompanyModel>();

	private Calendar myCalendar = Calendar.getInstance();
	private IPopupWindow popupSortby;
	private static ArrayList<InfoDoctorEntity> listInfoDoctor = new ArrayList<InfoDoctorEntity>();
	private static ArrayList<String> listDoctorName = new ArrayList<String>();
	private static StringBuilder data;
	private static String mData;
	private static String mTime;
	private ListInfoDoctorAdapter adapterDoctor;
	private Calendar cal;
	Date dateFinish;
	private Button spDateTime, btnSave, btnCancel;

	/*
	 * Data Spinner
	 */
	private ListView listPopupInput;
	private ArrayList<BasePopupModel> arrPopupInput;
	private Handler mHandler;
	private static int keyInputData = -1;
	private static int keyCom = -1;
	private static String ID_company = "";
	private static int keySaveBtn;
	/*
	 * Poppup Company
	 */
	private IPopupWindow popupCompany;
	private ArrayList<BasePopupModel> arrPopupCompany = new ArrayList<BasePopupModel>();
	private ListView lvPopupCompany;
	private BasePopupAdapter adapterCompany;

	/*
	 * Poppup Time Picker
	 */
	int mYear;
	int mMonth;
	int mDay;
	// waiting for loading data
	private ProgressBar pg_load;

	public static BMSDataEntryFragment newInstance() {
		BMSDataEntryFragment fragment = new BMSDataEntryFragment();
		Bundle bundle = new Bundle();
		fragment.setArguments(bundle);
		return fragment;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		IntentFilter filter = new IntentFilter();
		filter.addAction(IBMSConfig.KEY_ACTION_SHOW_TABLE_MEDICAL_RECORD);
		getActivity().registerReceiver(receiver, filter);

		super.onResume();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		getActivity().unregisterReceiver(receiver);
		super.onPause();
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// load list medical record follow hospital
			Bundle bundle = intent.getBundleExtra("BUNDLE");
			hospitalPosition = bundle.getInt("POSITION");
			lvHospitalAdapter.notifyDataSetChanged();
			lnTableType.setVisibility(View.GONE);
			BMSCore.getInstance(context).taskGetListMedicalRecordFollowHos(
					mTime, ID_company, hospitals.get(hospitalPosition).getId(),
					mPreferences.getUserAuthKey(getActivity()), listener);
			pg_load.setVisibility(View.VISIBLE);
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		cal = Calendar.getInstance();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);

		View v = inflater.inflate(R.layout.layout_input_data, container, false);
		mPreferences = new BMSSharedPreferences(getActivity());
		BMSCore.getInstance(getActivity()).taskGetListCompany(
				mPreferences.getUserAuthKey(getActivity()), listener);
//		pg_load.setVisibility(View.VISIBLE);
		spnInputData = (Button) v.findViewById(R.id.spn_type_input_data);
		spDateTime = (Button) v.findViewById(R.id.edt_select_date);
		btnSave = (Button) v.findViewById(R.id.btn_save_statistic);
		btnCancel = (Button) v.findViewById(R.id.btn_cancel_statistic);
		btnCancel.setOnClickListener(this);
		spnSelectCom = (Button) v.findViewById(R.id.spn_select_com);
		spnInputData.setHint(getResources().getString(R.string.select_info_));
		spnSelectCom
				.setHint(getResources().getString(R.string.select_company_));
		lnTableDoctor = (LinearLayout) v.findViewById(R.id.include_list_doctor);
		lvTableHos = (ListView) v.findViewById(R.id.lst_hospital);
		lvTableType = (ListView) v.findViewById(R.id.lst_type_schedule);

		lnSave = (LinearLayout) v.findViewById(R.id.ln_save_statistic);
		lnTime = (LinearLayout) v.findViewById(R.id.ln_time_statistic);
		lnTableHospital = (LinearLayout) v
				.findViewById(R.id.include_list_hospital);
		lnTableType = (LinearLayout) v
				.findViewById(R.id.include_list_type_schedule);
		//
		lvTableDoctor = (ListView) v.findViewById(R.id.lst_static_doctor);
		pg_load = (ProgressBar) v.findViewById(R.id.loading_data);
		pg_load.setVisibility(View.VISIBLE);

		spDateTime.setOnClickListener(this);
		spnInputData.setOnClickListener(this);
		spnSelectCom.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		return v;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.spn_type_input_data:
			loadDataPopupInput();
			break;
		case R.id.spn_select_com:
			loadDataPopupCompany();
			break;
		case R.id.btn_save_statistic:

			if (keySaveBtn == 1) {

				saveUpdateHosRecord();
			} else if (keySaveBtn == 2) {

				saveUpdateDoctor();
			}

			break;
		case R.id.edt_select_date:
			showDatePickerDialog();

			break;
		case R.id.btn_cancel_statistic:
			if (keySaveBtn == 1) {
				showTable(keyInputData, keyCom, spDateTime.getText().toString());
			} else if (keySaveBtn == 2) {
				showTable(keyInputData, keyCom, spDateTime.getText().toString());
			}
			break;
		default:
			break;
		}
	}

	private void saveUpdateDoctor() {
		ArrayList<InputDataModel> inputDataModels = new ArrayList<InputDataModel>();
		for (int i = 0; i < ListInfoDoctorAdapter.listInfoDoctor.size(); i++) {

			InputDataModel model = new InputDataModel(
					ListInfoDoctorAdapter.listInfoDoctor.get(i)
							.getComDoctorId(),
					ListInfoDoctorAdapter.listInfoDoctor.get(i)
							.getCoutSchedule(),
					ListInfoDoctorAdapter.listInfoDoctor.get(i).getRevenue());
			inputDataModels.add(model);
		}

		BMSCore.getInstance(getActivity()).taskSendUpdateComDoctor(
				inputDataModels, mTime,
				mPreferences.getUserAuthKey(getActivity()), listener);
		pg_load.setVisibility(View.VISIBLE);
	}

	private void saveUpdateHosRecord() {
		ArrayList<HospitalRecordInputDataModel> DataRecord = new ArrayList<HospitalRecordInputDataModel>();

		for (int i = 0; i < ListTypeScheduleAdapter.typeSchedules.size(); i++) {
			HospitalRecordInputDataModel model = new HospitalRecordInputDataModel(
					ListTypeScheduleAdapter.typeSchedules.get(i).getId(),
					ListTypeScheduleAdapter.typeSchedules.get(i)
							.getOperatin_count());
			DataRecord.add(model);
		}
		BMSCore.getInstance(getActivity()).taskSendUpdateHosAndRecord(
				hospitals.get(hospitalPosition).getID(),
				hospitals.get(hospitalPosition).getRevenue(), DataRecord,
				spDateTime.getText().toString(),
				mPreferences.getUserAuthKey(getActivity()), listener);
		pg_load.setVisibility(View.VISIBLE);
	}

	private void showDatePickerDialog() {

		DatePickerDialog pic = new DatePickerDialog(getActivity(),
				new OnDateSetListener() {

					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						// TODO Auto-generated method stub
						String Date = year + "-" + (monthOfYear + 1) + "-"
								+ dayOfMonth;
						spDateTime.setText(Date);
						if (keyCom != -1&&spnSelectCom.getText().toString()!="") {
							showTable(keyInputData, keyCom, Date);
							spnSelectCom.setText(arrPopupCompany.get(keyCom).getName());
						}

					}
				}, mYear, mMonth, mDay);
		pic.setTitle(getResources().getString(R.string.select_date_start));
		pic.show();
	}

	private void loadDataPopupInput() {
		if (popupSortby == null) {
			popupSortby = new IPopupWindow(getActivity(),
					R.layout.popup_sortby_layout, null, false,
					spnInputData.getMeasuredWidth(), LayoutParams.WRAP_CONTENT);
			listPopupInput = (ListView) popupSortby.getView().findViewById(
					R.id.listPopup);

			arrPopupInput = Utils.getDataPopupInput(getActivity(),
					R.array.arr_statistic_doctor_spin);
			final BasePopupAdapter adapter = new BasePopupAdapter(
					getActivity(), arrPopupInput);
			listPopupInput.setAdapter(adapter);
			popupSortby.setAutoHideOutside();
			popupSortby.showAsDropDown(spnInputData);
			listPopupInput.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					spnInputData.setText(arrPopupInput.get(position).getName());

					keyInputData = (arrPopupInput.get(position).getId());
					popupSortby.dismiss();
					if (spDateTime.getText().toString() != "") {
						showTable(keyInputData, keyCom, spDateTime.getText()
								.toString());
					}

				}
			});
		} else {
			popupSortby.showAsDropDown(spnInputData);
		}
	}

	private void loadDataPopupCompany() {
		if (popupCompany == null) {
			popupCompany = new IPopupWindow(getActivity(),
					R.layout.popup_sortby_layout, null, false,
					spnSelectCom.getMeasuredWidth(), LayoutParams.WRAP_CONTENT);
			lvPopupCompany = (ListView) popupCompany.getView().findViewById(
					R.id.listPopup);
			if (adapterCompany == null)
				adapterCompany = new BasePopupAdapter(getActivity(),
						arrPopupCompany);

			lvPopupCompany.setAdapter(adapterCompany);
			adapterCompany.notifyDataSetChanged();
			lvPopupCompany.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// TODO Auto-generated method stub
					popupCompany.dismiss();
					spnSelectCom.setText(arrPopupCompany.get(position)
							.getName());
					ID_company = listCompanies.get(position).getComID();
					lnTime.setVisibility(View.VISIBLE);
					keyCom = arrPopupCompany.get(position).getId();
					if (spDateTime.getText().toString() == "") {
						spDateTime.setText(DateTimeSystem
								.getDateMonthYearToServer());
						showTable(keyInputData, keyCom, spDateTime.getText()
								.toString());
					} else {
						showTable(keyInputData, keyCom, spDateTime.getText()
								.toString());
					}
					// showTable(keyInput,mTime);

				}
			});

			popupCompany.setAutoHideOutside();
			popupCompany.showAsDropDown(spnSelectCom);
		} else {
			lvPopupCompany.setAdapter(adapterCompany);
			adapterCompany.notifyDataSetChanged();
			popupCompany.showAsDropDown(spnSelectCom);
		}
	}

	private void showTable(int keyInt, int keyCompany, String Date) {
		// cho hien bag len o day
		if (keyInt == 0 && keyCompany != -1) {
			mTime = spDateTime.getText().toString();
			BMSCore.getInstance(getActivity()).taskGetComDoctor(
					mPreferences.getUserAuthKey(getActivity()),
					spDateTime.getText().toString(), ID_company, listener);
			pg_load.setVisibility(View.VISIBLE);
		} else if (keyInt == 1 && keyCompany != -1) {
			mTime = spDateTime.getText().toString();
			BMSCore.getInstance(getActivity()).taskGetListComHospital(
					spDateTime.getText().toString(), ID_company,
					mPreferences.getUserAuthKey(getActivity()), listener);
			pg_load.setVisibility(View.VISIBLE);
		}
	}

	class Listener extends BMSListener {

		@Override
		public void finishSendUpdateHosRecord(final int returnCode,
				String resultMsg) {
			// TODO Auto-generated method stub
			super.finishSendUpdateHosRecord(returnCode, resultMsg);
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					pg_load.setVisibility(View.GONE);
					if (returnCode == IBMSProtocol.STATUS_CODE_OK) {
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.sussess),
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.not_participation_schedule_fail),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
		}

		@Override
		public void finishGetListRecordMedicalHos(final int returnCode,
				final String resultMsg,
				final ArrayList<MedicalRecordModel> listRecords) {
			// TODO Auto-generated method stub
			super.finishGetListRecordMedicalHos(returnCode, resultMsg,
					listRecords);
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					pg_load.setVisibility(View.GONE);
					if (returnCode == IBMSProtocol.STATUS_CODE_OK
							&& listRecords.size() != 0) {
						records = listRecords;
						lnSave.setVisibility(View.VISIBLE);
						lvTSAdapter = new ListTypeScheduleAdapter(
								getActivity(), records);
						lvTableType.setAdapter(lvTSAdapter);
						lvTSAdapter.notifyDataSetChanged();
						UtilityListView
								.setListViewHeightBasedOnChildrenforWarranty(
										getActivity(), lvTableType);
						lnTableDoctor.setVisibility(View.GONE);
						lnTime.setVisibility(View.VISIBLE);
						lnSave.setVisibility(View.VISIBLE);
						lnTableType.setVisibility(View.VISIBLE);
						keySaveBtn = 1;
						Toast.makeText(getActivity(),  getActivity().getResources().getString(R.string.sussess),
								Toast.LENGTH_SHORT).show();
						lnTableType.setVisibility(View.VISIBLE);
						// lvTableType.setVisibility(View.VISIBLE);
					} else {
						Toast.makeText(getActivity(),getActivity().getResources().getString(R.string.error_data_server),
								Toast.LENGTH_SHORT).show();
					}

				}

			});
		}

		@Override
		public void finishSendUpdateComDoctor(final int returnCode,
				final String resultMsg) {
			// TODO Auto-generated method stub
			super.finishSendUpdateComDoctor(returnCode, resultMsg);
			getActivity().runOnUiThread(new Runnable() {
				
				public void run() {
					pg_load.setVisibility(View.GONE);
					if (returnCode == IBMSProtocol.STATUS_CODE_OK) {
						Toast.makeText(getActivity(),  getActivity().getResources().getString(R.string.sussess),
								Toast.LENGTH_SHORT).show();
					} else if(returnCode==IBMSProtocol.STATUS_CODE_EXIT_RECORD) {
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_data_server),
								Toast.LENGTH_SHORT).show();
					}
					else{
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.fail),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
		}

		@Override
		public void finishGetComDoctor(final int returnCode, String resultMsg,
				final ArrayList<InfoDoctorEntity> arrayList) {
			// TODO Auto-generated method stub
			super.finishGetComDoctor(returnCode, resultMsg, arrayList);
			
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					pg_load.setVisibility(View.GONE);
					if (returnCode == IBMSProtocol.STATUS_CODE_OK) {
						listInfoDoctor = arrayList;
						adapterDoctor = new ListInfoDoctorAdapter(
								getActivity(), listInfoDoctor);
						lvTableDoctor.setAdapter(adapterDoctor);

						UtilityListView
								.setListViewHeightBasedOnChildrenforWarranty(
										getActivity().getApplicationContext(),
										lvTableDoctor);
						lnTableDoctor.setVisibility(View.VISIBLE);
						lnTime.setVisibility(View.VISIBLE);
						lnSave.setVisibility(View.VISIBLE);
						lnTableHospital.setVisibility(View.GONE);
						lnTableType.setVisibility(View.GONE);
						adapterDoctor.notifyDataSetChanged();
						
						String a = listInfoDoctor.size() > 0 ? listInfoDoctor.get(0).getNameDoctor() : "";
						Log.v("LOG", "aa" + a);
						keySaveBtn = 2;
//						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.sussess),
//								Toast.LENGTH_SHORT).show();

					}
					else if(returnCode==IBMSProtocol.STATUS_CODE_EXIT_RECORD){
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_data_server),
								Toast.LENGTH_SHORT).show();
					} 
					else{
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.fail),
								Toast.LENGTH_SHORT).show();
					}
				}
			});
		}

		@Override
		public void finishGetListCompany(final int returnCode,
				String resultMsg, final ArrayList<CompanyModel> listComs) {
			// TODO Auto-generated method stub
			super.finishGetListCompany(returnCode, resultMsg, listComs);

			getActivity().runOnUiThread(new Runnable() {

				public void run() {
					pg_load.setVisibility(View.GONE);
					if (returnCode == IBMSProtocol.STATUS_CODE_OK
							&& listComs.size() != 0) {
						listCompanies = listComs;

						for (CompanyModel model : listComs) {
							arrPopupCompany.add(new BasePopupModel(Integer
									.parseInt(model.getComID()), model
									.getComName(), Integer.parseInt(model
									.getComID())));
						}
						if (adapterCompany == null)
							adapterCompany = new BasePopupAdapter(
									getActivity(), arrPopupCompany);
						adapterCompany.notifyDataSetChanged();
//						Toast.makeText(getActivity(),  getActivity().getResources().getString(R.string.sussess),
//								Toast.LENGTH_SHORT).show();

					} else if (returnCode == IBMSProtocol.STATUS_CODE_EXIT_RECORD) {

						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_data_server),
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(getActivity(),  getActivity().getResources().getString(R.string.fail),
								Toast.LENGTH_SHORT).show();
					}

				}
			});

		}

		@Override
		public void finishGetListComHopital(final int returnCode,
				String resultMsg, final ArrayList<Hospital> listHopital) {
			// TODO Auto-generated method stub
			super.finishGetListComHopital(returnCode, resultMsg, listHopital);

			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					pg_load.setVisibility(View.GONE);
					if (returnCode == IBMSProtocol.STATUS_CODE_OK
							&& listHopital != null) {
						hospitals = listHopital;
						lvHospitalAdapter = new ListHospitalAdapter(
								getActivity(), hospitals);
						lvTableHos.setAdapter(lvHospitalAdapter);
						lvHospitalAdapter.notifyDataSetChanged();
						lnTableHospital.setVisibility(View.VISIBLE);
						lnTableDoctor.setVisibility(View.GONE);
						// lnTime.setVisibility(View.GONE);
						lnSave.setVisibility(View.GONE);
						UtilityListView
								.setListViewHeightBasedOnChildrenforWarranty(
										getActivity().getApplicationContext(),
										lvTableHos);
						lnTableType.setVisibility(View.GONE);
//						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.sussess),
//								Toast.LENGTH_SHORT).show();

					}else if(returnCode==IBMSProtocol.STATUS_CODE_GENERIC_FAIL){
						Toast.makeText(getActivity(),getActivity().getResources().getString(R.string.error_perpose), Toast.LENGTH_SHORT).show();
					}else if(returnCode==IBMSProtocol.STATUS_CODE_GENERIC_FAIL_CONECTTION){
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_network_connection), Toast.LENGTH_SHORT).show();
					}else if(returnCode==IBMSProtocol.STATUS_CODE_EXIT_RECORD){
						Toast.makeText(getActivity(), getActivity().getResources().getString(R.string.error_data_server), Toast.LENGTH_SHORT).show();
					} 

				}
			});
		}

	}

}